package com.example.starter.security.configure;

import cn.hutool.core.util.ArrayUtil;
import com.example.starter.security.component.ExampleRemoteTokenServices;
import com.example.starter.security.handler.ExampleAuthenticationEntryPoint;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.client.RestTemplate;


/**
 * @author 王令
 * @since 2022/8/9 21:06
 */
@RequiredArgsConstructor
public class OAuth2ResourceConfiguration extends ResourceServerConfigurerAdapter {

    private final SecurityProperties properties;
    private final RestTemplate restTemplate;
    private final TokenStore tokenStore;

    @SneakyThrows
    @Override
    public void configure(HttpSecurity http) {
        http
                .authorizeRequests()
                .antMatchers(ArrayUtil.toArray(properties.getPermitUrls(), String.class)).permitAll()
                .anyRequest().authenticated();
    }

    @SneakyThrows
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.tokenServices(remoteTokenServices())
                .authenticationEntryPoint(new ExampleAuthenticationEntryPoint());
    }

    /**
     * 资源服务令牌解析服务,调用远程服务解析
     */
    public ResourceServerTokenServices remoteTokenServices() {
        ExampleRemoteTokenServices remoteTokenServices = new ExampleRemoteTokenServices(restTemplate, tokenStore);
        remoteTokenServices.setCheckTokenEndpointUrl(properties.getCheckTokenEndpointUrl());
        return remoteTokenServices;
    }


}
